/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveExportFiles : CommandUtils.GrooveUtilBase
	{
		private string m_SpaceURI;
		private string m_FilesToolURI;
		private string m_TargetPath;

		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveExportFiles(i_Arguments));
		}

		public GrooveExportFiles(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveExportFiles [PARAMS...]";
			base.HelpMessage = 
				"GrooveExportFiles\r\n\t" + 
				"Exports all files and folders from all files tools from specified space(s)\r\n" +
				"Parameters:\r\n\t" +
				"/Space=              The Web Services URI for the Groove space or * for all\r\n\t" +
				"/TargetPath          Path to where all folders and files will be exported\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/FilesTool=         The Web Services URI for the Groove files tool]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;
		
			m_SpaceURI = base.GetParameterValue("Space");
			if (System.String.IsNullOrEmpty(m_SpaceURI))
			{
				base.DisplayUsage("You must specify a space.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			m_FilesToolURI = base.GetParameterValue("FilesTool");

			m_TargetPath = base.GetParameterValue("TargetPath");
			if (System.String.IsNullOrEmpty(m_TargetPath))
			{
				base.DisplayUsage("You must specify a target path.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			if (m_SpaceURI == "*")
			{
				//  Process all spaces
				GrooveWebServicesV12Helpers.Space[] Spaces = null;

				try
				{
					Spaces = base.Identity.StandardSpaces;
				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to get spaces: " + Exception.Message);
					return CommandUtils.UtilBase.CheckResult.Failed;
				}

				foreach (GrooveWebServicesV12Helpers.Space Space in Spaces)
				{
					try
					{
						ProcessSpace(Space, m_TargetPath);
					}
					catch (System.Exception Exception)
					{
						base.StandardError.WriteLine("Unable to process space: " + Exception.Message);
						return CommandUtils.UtilBase.CheckResult.Failed;
					}
				}
			}
			else
			{
				//  Process specified space only
				GrooveWebServicesV12Helpers.Space Space = null;

				try
				{
					Space = base.Identity.OpenSpace(m_SpaceURI);
				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to open space: " + Exception.Message);
					return CommandUtils.UtilBase.CheckResult.Failed;
				}

				try
				{
					ProcessSpace(Space, m_TargetPath);
				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to process space: " + Exception.Message);
					throw Exception;
				}
			}
		
			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}

		private void ProcessSpace(GrooveWebServicesV12Helpers.Space i_Space, string i_TargetPath)
		{
			string[] SupportedTypes = new string[] {GrooveWebServicesV12Helpers.Shared.GROOVE_FILES_TOOL_SUPPORTED_TYPE};
			GrooveWebServicesV12Helpers.Tool[] Tools = null;
			
			try
			{
				Tools = i_Space.GetToolsBySupportedTypes(SupportedTypes);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("\nUnable to get tools by supported type: " + Exception.Message);
				throw Exception;
			}

			//  If no Files tools found, just exit now
			if (Tools.Length == 0)
				return;

			string[] SpaceURIParts = i_Space.URI.Split(new char[] {'/'});
			string SpaceID = SpaceURIParts[SpaceURIParts.Length - 1];
			
			foreach (GrooveWebServicesV12Helpers.Files.FilesTool FilesTool in Tools)
			{
				//  Check for specified files tool uri, continue loop if not same
				if (!System.String.IsNullOrEmpty(m_FilesToolURI) && (FilesTool.URI != m_FilesToolURI))
					continue;
				
				FilesTool.RootFolder.Export(i_TargetPath);
			}
		}
	}
}
